package com.pet_service.upload;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-09-23 22:43
 */

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * MinIO图片存储工具类（专门用于用户头像和宠物图片）
 */
public class MinIOUtil {

    public static final String ENDPOINT = "http://192.168.88.128:9001";
    public static final String ACCESS_KEY = "admin";
    public static final String SECRET_KEY = "admin123";
    public static final String DEFAULT_BUCKET = "petservice";//存储桶名称



    private static MinioClient minioClient;

    static {
        try {
            minioClient = MinioClient.builder()
                    .endpoint(ENDPOINT)
                    .credentials(ACCESS_KEY, SECRET_KEY)
                    .build();
        } catch (Exception e) {
            throw new RuntimeException("初始化MinIO客户端失败", e);
        }
    }

    /**
     * 获取MinioClient实例
     * @return MinioClient
     */
    public static MinioClient getMinioClient() {
        return minioClient;
    }

    /**
     * 检查存储桶是否存在
     * @param bucketName 存储桶名称
     * @return 是否存在
     */
    public static boolean bucketExists(String bucketName) {
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException("检查存储桶失败: " + e.getMessage(), e);
        }
    }

    /**
     * 创建存储桶
     * @param bucketName 存储桶名称
     */
    public static void createBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException("创建存储桶失败: " + e.getMessage(), e);
        }
    }

    /**
     * 设置存储桶访问策略（公开读）
     * @param bucketName 存储桶名称
     */
    public static void setBucketPublicPolicy(String bucketName) {
        try {
            String policy = """
                    {
                      "Statement" : [ {
                        "Action" : "s3:GetObject",
                        "Effect" : "Allow",
                        "Principal" : "*",
                        "Resource" : "arn:aws:s3:::%s/*"
                      } ],
                      "Version" : "2012-10-17"
                    }""".formatted(bucketName);
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
        } catch (Exception e) {
            throw new RuntimeException("设置存储桶策略失败: " + e.getMessage(), e);
        }
    }

    /**
     * 确保存储桶存在并设置公开读权限
     * @param bucketName 存储桶名称
     */
    public static void ensureBucketExists(String bucketName) {
        try {
            if (!bucketExists(bucketName)) {
                createBucket(bucketName);
                setBucketPublicPolicy(bucketName);
            }
        } catch (Exception e) {
            throw new RuntimeException("确保存储桶存在失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取文件扩展名
     * @param fileName 文件名
     * @return 扩展名
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 生成唯一文件名
     * @param originalFileName 原始文件名
     * @return 唯一文件名
     */
    public static String generateUniqueFileName(String originalFileName) {
        String extension = getFileExtension(originalFileName);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid + (extension.isEmpty() ? "" : "." + extension);
    }

    /**
     * 验证是否为有效的图片文件
     * @param file MultipartFile文件
     * @return 是否为有效图片
     */
    public static boolean isValidImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        String contentType = file.getContentType();
        if (contentType == null) {
            return false;
        }

        // 支持的图片格式
        return contentType.startsWith("image/") &&
                (contentType.contains("jpeg") ||
                        contentType.contains("jpg") ||
                        contentType.contains("png") ||
                        contentType.contains("gif") ||
                        contentType.contains("webp"));
    }




    /**
     * 获取文件访问URL
     * @param bucketName 存储桶名称
     * @param objectName 对象名称
     * @return 文件访问URL
     */
    public static String getFileUrl(String bucketName, String objectName) {
        return ENDPOINT + "/" + bucketName + "/" + objectName;
    }


}
